package com.wenjie.gateway;

import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWT;
import com.wenjie.common.unifiedReturn.Result;
import com.wenjie.common.utils.StringUtils;
import com.wenjie.gateway.exception.NoLoginException;
import com.wenjie.utils.EnvironmentUtils;
import com.wenjie.utils.RequestUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CheckInterceptor implements HandlerInterceptor {

//    private final String scret = "wenjie0101_jwt";


    /**
     * @Description: TODO 拦截方法
     * @Param:
     * @Return:
     * @Author: wenjie
     * @Date: 2023/1/18
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        try {
            if ("OPTIONS".equalsIgnoreCase(request.getMethod())) return true;
            if ("ERROR".equals(request.getDispatcherType().name())) return true;
            if (request.getRequestURI().length() < 5 || !"/api".equals(request.getRequestURI().substring(0, 4)))
                return true;
            String token = request.getHeader("token");
            if (StringUtils.isNotBlank(token)) {
                JWT jwtToken = JWT.of(token).setKey(EnvironmentUtils.getStr("jwt.token.secretKey").getBytes());
                if (!jwtToken.validate(0)) throw new NoLoginException("登录时间过期 请重新登录");
                if (jwtToken.verify()) return true;
                else throw new NoLoginException("校验异常,请重新登录");
            }
            throw new NoLoginException("请登录");
        } catch (NoLoginException e) {
            RequestUtils.directSuccessReturn(response, JSONUtil.toJsonStr(Result.create(ResConstant.NO_LOGIN, e.getMessage())));
            return false;
        }
    }


}
